<?php

namespace App\Http\Controllers\V1;

use App\Http\Requests\WithdrawRequest;
use App\Http\Controllers\Controller;
use App\Models\Withdrawal;
use App\Service\UserFlowService;
use EasyWeChat\Factory;
use Flaravel\FLaravelSms;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;

class WithdrawController extends Controller
{
    use ThrottlesLogins;

    // 提现
    public function store(WithdrawRequest $request)
    {
        //验证登录次数
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        $user = $request->user();

        if ($user->withdrawal()->where('status', 2)->exists()) {
            return $this->failed('您有一个提现订单正在等待审核...');
        }
        $withdrawalAmount = $request->withdrawal_amount;

        $comp = bccomp($user->gourd_coin, $withdrawalAmount);

        if ($comp == -1) {
            return $this->failed('葫芦币余额不足');
        }
        // 提现
        $withdrawal = new Withdrawal([
            'member_id' => $user->id,
            'withdrawal_amount' => $withdrawalAmount,
            'realname' => $request->realname,
            'desc' => ''
        ]);
        $withdrawal->save();
        if ($withdrawal) {
            $this->incrementLoginAttempts($request);
            $app = Factory::payment(config('wechat.payment.default'));
            $res = $app->transfer->toBalance([
                'partner_trade_no' => $withdrawal->withdrawal_sn,
                'openid' => $user->wx_mini_openid,
                'check_name' => 'FORCE_CHECK',
                're_user_name' => $withdrawal->realname,
                'amount' => bcmul($withdrawal->withdrawal_amount, 100),
                'desc' => '葫芦币提现',
            ]);
            // 付款成功
            if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
                $withdrawal->desc = '葫芦币提现成功';
                $withdrawal->payment_no = $res['payment_no'];
                $withdrawal->status = 1;
                $withdrawal->save();
                // 减少葫芦币
                $user->decrement('gourd_coin', $withdrawal->withdrawal_amount);
                // 增加流水
                $desc = sprintf('葫芦币提现-%d', $withdrawal->withdrawal_amount);
                (new UserFlowService())->create($user, 1, $desc,  -$withdrawal->withdrawal_amount);
                FLaravelSms::notice($user->phone, 'withdraw_up', [
                    'price' => $withdrawal->withdrawal_amount
                ]);
                return $this->message('提现成功');
            } else {
                if ($res['err_code'] == 'NO_AUTH') {
                    $withdrawal->desc = '葫芦币提现申请成功，需人工进行汇款,失败原因:'.$res['err_code_des'];
                    $withdrawal->status = 2;
                    $withdrawal->save();
                    return $this->success('提现成功，请等待系统审核');
                } else {
                    $withdrawal->desc = '葫芦币提现失败,失败原因:'.$res['err_code_des'];
                    $withdrawal->status = 3;
                    $withdrawal->save();
                }
                return $this->failed('提现失败，请联系客服');
            }
        }
    }


    /**
     * 返回验证次数的凭证，一般用用户名
     *
     * @return string
     */
    protected function username()
    {
        return 'realname';
    }

    /**
     * 自定义多次输入错误返回错误信息
     *
     * @param Request $request
     * @return mixed
     */
    protected function sendLockoutResponse(Request $request)
    {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );
        return $this->failed(Lang::get('auth.withdraw', ['seconds' => $seconds]));
    }
}
